package com.wss.lsl.test.driven.concurrent;

import java.math.BigInteger;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

import org.junit.Assert;

/**
 * 无效的取消任务的方案：任务可能永远处于阻塞状态
 * 
 * @author Administrator
 * 
 */
public class BrokenPrimeProducer extends Thread {

	private BlockingQueue<BigInteger> queue;
	private CountDownLatch begin;
	private CountDownLatch end;
	private volatile boolean cancelled = false;

	public BrokenPrimeProducer(CountDownLatch begin,
			BlockingQueue<BigInteger> queue, CountDownLatch end) {
		super();
		this.begin = begin;
		this.queue = queue;
		this.end = end;
	}

	@Override
	public void run() {

		try {
			BigInteger p = BigInteger.ONE;
			while (!cancelled) {
				System.out.println("put");
				begin.countDown();
				queue.put(p.nextProbablePrime());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			end.countDown();
		}
	}

	public synchronized void cancel() {
		cancelled = true;
	}

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<BigInteger> queue = new ArrayBlockingQueue<BigInteger>(2);
		queue.put(new BigInteger("1"));
		queue.put(new BigInteger("2"));

		CountDownLatch begin = new CountDownLatch(1);
		CountDownLatch end = new CountDownLatch(1);

		BrokenPrimeProducer producer = new BrokenPrimeProducer(begin, queue,
				end);
		producer.start();

		begin.await();
		producer.cancel();
		System.out.println("任务已经取消");
		Assert.assertEquals(Thread.State.WAITING, producer.getState());
		System.out.println("Done!");

		end.await();
	}

}
